<template>
  <view class="tab-bar">
    <view
      v-for="(item, index) in tabs"
      :key="item.id"
      class="tab-item"
      :class="{ active: currentTab === item.id }"
      @click="changeTab(item.id, item.url)"
    >
      <uni-icons
        :type="currentTab === item.id ? item.iconActive : item.icon"
        size="24"
        :color="currentTab === item.id ? '#5a8dee' : '#999'"
      ></uni-icons>
      <text class="tab-text">{{ item.text }}</text>
    </view>
  </view>
  <!-- 底部安全区域，适配全面屏手机 -->
  <view class="safe-area-inset-bottom"></view>
</template>

<script setup>
import { ref, onMounted } from "vue";

// 组件属性
const props = defineProps({
  // 当前选中标签
  current: {
    type: Number,
    default: 0,
  },
  // 标签项
  tabs: {
    type: Array,
    default: () => [
      {
        id: 0,
		icon: "home",
        iconActive: "home-filled",
        text: "首页",
        url: "/pages/index/index",
      },
      {
		id: 1,
        icon: "list",
        iconActive: "list",
        text: "展品",
        url: "/pages/exhibition/index",
      },
      {
        id: 2,
		icon: "calendar",
        iconActive: "calendar-filled",
        text: "预约",
        url: "/pages/booking/index",
      },
      {
        id: 3,
		icon: "person",
        iconActive: "person-filled",
        text: "我的",
        url: "/pages/profile/index",
      },
    ],
  },
});

// 事件
const emit = defineEmits(["change"]);

// 当前选中的标签
const currentTab = ref(props.current);

// 切换标签
const changeTab = (index, url) => {
  if (currentTab.value === index) return;
  emit("change", index);

  // 跳转到对应页面
  uni.switchTab({
    url,
    fail() {
      // 如果不是 tabBar 页面，使用 navigateTo
      uni.navigateTo({
        url,
      });
    },
  });
};

// 组件挂载时设置当前选中项
onMounted(() => {
  currentTab.value = props.current;
});
</script>

<style lang="scss" scoped>
.tab-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100vw;
  height: 100rpx;
  background-color: #ffffff;
  display: flex;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: $zindex-fixed;

  .tab-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: $spacer-1 0;

    &.active {
      .tab-text {
        color: $uni-color-primary;
      }
    }
  }

  .tab-text {
    font-size: $uni-font-size-sm;
    color: $uni-text-color-grey;
    margin-top: $spacer-1;
  }
}

// 底部安全区域
.safe-area-inset-bottom {
  height: constant(safe-area-inset-bottom);
  height: env(safe-area-inset-bottom);
  width: 100%;
}
</style>
